import { useEffect, useCallback, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { authService } from '../services/auth';
import { useLocalizedLink } from '@kernelproxy/i18n';

interface UseSessionMonitorOptions {
  /**
   * Check interval in milliseconds
   * @default 60000 (1 minute)
   */
  checkInterval?: number;
  
  /**
   * Warn user when session expires in less than this time (milliseconds)
   * @default 300000 (5 minutes)
   */
  warnThreshold?: number;
  
  /**
   * Callback when session is about to expire
   */
  onSessionExpiring?: (timeRemaining: number) => void;
  
  /**
   * Callback when session has expired
   */
  onSessionExpired?: () => void;
}

export const useSessionMonitor = (options: UseSessionMonitorOptions = {}) => {
  const {
    checkInterval = 60000, // Check every minute
    warnThreshold = 300000, // Warn 5 minutes before expiry
    onSessionExpiring,
    onSessionExpired
  } = options;

  const { isAuthenticated, logout } = useAuth();
  const navigate = useNavigate();
  const { getLink } = useLocalizedLink();
  const intervalRef = useRef<NodeJS.Timeout | null>(null);
  const hasWarnedRef = useRef(false);

  const checkSession = useCallback(async () => {
    if (!isAuthenticated) {
      return;
    }

    try {
      const result = await authService.checkSessionExpiry();
      
      if (!result.success || !result.timeUntilExpiry) {
        // Session is invalid or expired
        if (onSessionExpired) {
          onSessionExpired();
        }
        await logout();
        navigate(getLink('/login?session=expired'));
        return;
      }

      const timeUntilExpiry = result.timeUntilExpiry;

      // Check if session is about to expire
      if (timeUntilExpiry < warnThreshold && !hasWarnedRef.current) {
        hasWarnedRef.current = true;
        if (onSessionExpiring) {
          onSessionExpiring(timeUntilExpiry);
        }
      }

      // Reset warning if session was extended
      if (timeUntilExpiry >= warnThreshold) {
        hasWarnedRef.current = false;
      }

      // Auto-logout if session expired
      if (timeUntilExpiry <= 0) {
        if (onSessionExpired) {
          onSessionExpired();
        }
        await logout();
        navigate(getLink('/login?session=expired'));
      }
    } catch (error) {
      console.error('Session check failed:', error);
    }
  }, [isAuthenticated, logout, navigate, getLink, warnThreshold, onSessionExpiring, onSessionExpired]);

  useEffect(() => {
    if (isAuthenticated) {
      // Initial check
      checkSession();

      // Set up interval
      intervalRef.current = setInterval(checkSession, checkInterval);
    }

    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
        intervalRef.current = null;
      }
    };
  }, [isAuthenticated, checkSession, checkInterval]);

  /**
   * Extend the current session
   */
  const extendSession = useCallback(async () => {
    try {
      const result = await authService.updateSession();
      if (result.success) {
        hasWarnedRef.current = false;
        return true;
      }
      return false;
    } catch (error) {
      console.error('Failed to extend session:', error);
      return false;
    }
  }, []);

  return {
    extendSession,
    checkSession
  };
};
